<template>
  <div class="software-container">
    <el-card class="header-card">
      <div class="header-content">
        <div>
          <h2>📦 软件共享中心</h2>
          <p class="subtitle">提供常用软件下载服务</p>
        </div>
        <el-button v-if="isAdmin" type="primary" @click="showAddDialog">
          <el-icon><Plus /></el-icon>
          添加软件
        </el-button>
      </div>
    </el-card>

    <!-- 分类和搜索 -->
    <el-card class="filter-card">
      <div class="filter-content">
        <div class="categories">
          <el-button
            :type="currentCategory === null ? 'primary' : ''"
            @click="filterByCategory(null)"
            size="small"
          >
            全部
          </el-button>
          <el-button
            v-for="cat in categories"
            :key="cat.id"
            :type="currentCategory === cat.id ? 'primary' : ''"
            @click="filterByCategory(cat.id)"
            size="small"
          >
            {{ cat.icon }} {{ cat.name }}
          </el-button>
        </div>
        <el-input
          v-model="searchKeyword"
          placeholder="搜索软件名称..."
          clearable
          @clear="loadSoftware"
          @keyup.enter="loadSoftware"
          style="width: 300px"
        >
          <template #append>
            <el-button @click="loadSoftware" :icon="Search" />
          </template>
        </el-input>
      </div>
    </el-card>

    <!-- 软件列表 -->
    <div class="software-grid">
      <el-card
        v-for="software in softwareList"
        :key="software.id"
        class="software-card"
        shadow="hover"
      >
        <div class="software-icon">
          {{ software.category_icon || '📦' }}
        </div>
        <h3 class="software-name">{{ software.name }}</h3>
        <div class="software-version">v{{ software.version || '1.0' }}</div>
        <p class="software-desc">{{ software.description || '暂无描述' }}</p>
        <div class="software-meta">
          <span class="meta-item">
            <el-icon><Download /></el-icon>
            {{ software.download_count }}
          </span>
          <span class="meta-item">
            <el-icon><Folder /></el-icon>
            {{ software.category_name }}
          </span>
        </div>
        <div class="software-actions">
          <el-button type="primary" size="small" @click="downloadSoftware(software)" style="flex: 1">
            <el-icon><Download /></el-icon>
            下载
          </el-button>
          <el-button size="small" @click="viewDetails(software)">
            <el-icon><View /></el-icon>
            详情
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 分页 -->
    <el-pagination
      v-if="total > pageSize"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :total="total"
      layout="total, prev, pager, next"
      @current-change="loadSoftware"
      class="pagination"
    />

    <!-- 软件详情对话框 -->
    <el-dialog v-model="detailsVisible" title="软件详情" width="600px">
      <div v-if="currentSoftware" class="details-content">
        <div class="details-header">
          <div class="details-icon">{{ currentSoftware.category_icon || '📦' }}</div>
          <div>
            <h2>{{ currentSoftware.name }}</h2>
            <p>版本: {{ currentSoftware.version }}</p>
          </div>
        </div>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="分类">
            {{ currentSoftware.category_name }}
          </el-descriptions-item>
          <el-descriptions-item label="下载次数">
            {{ currentSoftware.download_count }}
          </el-descriptions-item>
          <el-descriptions-item label="开发者">
            {{ currentSoftware.developer || '未知' }}
          </el-descriptions-item>
          <el-descriptions-item label="文件大小">
            {{ formatFileSize(currentSoftware.file_size) }}
          </el-descriptions-item>
          <el-descriptions-item label="描述" :span="2">
            {{ currentSoftware.description || '暂无描述' }}
          </el-descriptions-item>
          <el-descriptions-item v-if="currentSoftware.website" label="官网" :span="2">
            <el-link :href="currentSoftware.website" target="_blank" type="primary">
              {{ currentSoftware.website }}
            </el-link>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <el-button @click="detailsVisible = false">关闭</el-button>
        <el-button type="primary" @click="downloadSoftware(currentSoftware)">
          <el-icon><Download /></el-icon>
          立即下载
        </el-button>
      </template>
    </el-dialog>

    <!-- 添加软件对话框（管理员） -->
    <el-dialog v-model="addDialogVisible" title="添加软件" width="600px">
      <el-form :model="softwareForm" label-width="100px">
        <el-form-item label="软件名称" required>
          <el-input v-model="softwareForm.name" />
        </el-form-item>
        <el-form-item label="版本号">
          <el-input v-model="softwareForm.version" placeholder="例如: 1.0.0" />
        </el-form-item>
        <el-form-item label="分类" required>
          <el-select v-model="softwareForm.categoryId" placeholder="选择分类">
            <el-option
              v-for="cat in categories"
              :key="cat.id"
              :label="`${cat.icon} ${cat.name}`"
              :value="cat.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="softwareForm.description" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="开发者">
          <el-input v-model="softwareForm.developer" />
        </el-form-item>
        <el-form-item label="官网">
          <el-input v-model="softwareForm.website" placeholder="https://" />
        </el-form-item>
        <el-form-item label="文件ID">
          <el-input v-model="softwareForm.fileId" placeholder="关联的文件ID" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="createSoftware">创建</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Download, View, Folder } from '@element-plus/icons-vue'
import axios from 'axios'

const categories = ref([])
const softwareList = ref([])
const currentCategory = ref(null)
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)

const detailsVisible = ref(false)
const currentSoftware = ref(null)

const addDialogVisible = ref(false)
const softwareForm = ref({
  name: '',
  version: '',
  categoryId: null,
  description: '',
  developer: '',
  website: '',
  fileId: null
})

const isAdmin = computed(() => {
  const user = JSON.parse(localStorage.getItem('user') || '{}')
  return user.role === 'admin'
})

// 加载分类
async function loadCategories() {
  try {
    const res = await axios.get('/api/software/categories')
    if (res.data.success) {
      categories.value = res.data.data
    }
  } catch (error) {
    console.error('加载分类失败:', error)
  }
}

// 加载软件列表
async function loadSoftware() {
  try {
    const params = {
      page: currentPage.value,
      limit: pageSize.value
    }

    if (currentCategory.value) {
      params.categoryId = currentCategory.value
    }

    if (searchKeyword.value) {
      params.keyword = searchKeyword.value
    }

    const res = await axios.get('/api/software', { params })
    if (res.data.success) {
      softwareList.value = res.data.data.software
      total.value = res.data.data.total
    }
  } catch (error) {
    console.error('加载软件列表失败:', error)
    ElMessage.error('加载软件列表失败')
  }
}

// 分类筛选
function filterByCategory(categoryId) {
  currentCategory.value = categoryId
  currentPage.value = 1
  loadSoftware()
}

// 查看详情
async function viewDetails(software) {
  try {
    const res = await axios.get(`/api/software/${software.id}`)
    if (res.data.success) {
      currentSoftware.value = res.data.data
      detailsVisible.value = true
    }
  } catch (error) {
    console.error('获取详情失败:', error)
    ElMessage.error('获取详情失败')
  }
}

// 下载软件
async function downloadSoftware(software) {
  try {
    const res = await axios.post(`/api/software/${software.id}/download`)
    if (res.data.success) {
      const { downloadUrl, fileName } = res.data.data
      
      // 创建下载链接
      const link = document.createElement('a')
      link.href = downloadUrl
      link.download = fileName
      link.click()
      
      ElMessage.success('开始下载...')
      loadSoftware() // 刷新列表以更新下载次数
    }
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error('下载失败')
  }
}

// 显示添加对话框
function showAddDialog() {
  softwareForm.value = {
    name: '',
    version: '',
    categoryId: null,
    description: '',
    developer: '',
    website: '',
    fileId: null
  }
  addDialogVisible.value = true
}

// 创建软件
async function createSoftware() {
  if (!softwareForm.value.name || !softwareForm.value.categoryId) {
    ElMessage.warning('请填写必填项')
    return
  }

  try {
    const res = await axios.post('/api/software', softwareForm.value)
    if (res.data.success) {
      ElMessage.success('软件创建成功')
      addDialogVisible.value = false
      loadSoftware()
    }
  } catch (error) {
    console.error('创建软件失败:', error)
    ElMessage.error('创建软件失败')
  }
}

// 格式化文件大小
function formatFileSize(bytes) {
  if (!bytes) return '未知'
  const units = ['B', 'KB', 'MB', 'GB']
  let size = bytes
  let unitIndex = 0
  while (size >= 1024 && unitIndex < units.length - 1) {
    size /= 1024
    unitIndex++
  }
  return `${size.toFixed(2)} ${units[unitIndex]}`
}

onMounted(() => {
  loadCategories()
  loadSoftware()
})
</script>

<style scoped>
.software-container {
  padding: 20px;
}

.header-card {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.subtitle {
  margin: 5px 0 0;
  color: #909399;
  font-size: 14px;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 20px;
}

.categories {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  flex: 1;
}

.software-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.software-card {
  transition: all 0.3s;
}

.software-card:hover {
  transform: translateY(-5px);
}

.software-icon {
  font-size: 48px;
  text-align: center;
  margin-bottom: 15px;
}

.software-name {
  font-size: 18px;
  font-weight: 600;
  margin: 0 0 8px;
  color: #303133;
  text-align: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.software-version {
  text-align: center;
  color: #909399;
  font-size: 13px;
  margin-bottom: 12px;
}

.software-desc {
  font-size: 14px;
  color: #606266;
  margin: 0 0 15px;
  height: 40px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.software-meta {
  display: flex;
  justify-content: space-around;
  padding: 10px 0;
  border-top: 1px solid #ebeef5;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 15px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 13px;
  color: #909399;
}

.software-actions {
  display: flex;
  gap: 10px;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.details-content {
  padding: 20px 0;
}

.details-header {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
}

.details-icon {
  font-size: 64px;
}

.details-header h2 {
  margin: 0;
  font-size: 24px;
}

.details-header p {
  margin: 5px 0 0;
  color: #909399;
}
</style>

